package com.hengyue.common.converter;

import com.hengyue.common.core.baseenum.IBaseEnum;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * 枚举转换数据库列
 * @param <X>
 */
@Converter
@SuppressWarnings("all")
public abstract class EnumAttributeConverter<X extends IBaseEnum<X>> implements AttributeConverter<X, Integer> {

    private final Class<X> clazz;
    private Method valuesMethod;


    public EnumAttributeConverter() {
        this.clazz = (Class<X>) (((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments())[0];
        try {
            valuesMethod = clazz.getMethod("values");
        } catch (Exception e) {
            throw new RuntimeException(clazz + "找不values方法");
        }
    }

    @Override
    public Integer convertToDatabaseColumn(X attribute) {
        return attribute == null ? null : attribute.getCode();
    }

    @Override
    public X convertToEntityAttribute(Integer dbData) {
        if(dbData == null){
            return null;
        }
        try {
            X[] values = (X[]) valuesMethod.invoke(null);
            for (X x : values) {
                if (x.getCode().equals(dbData)) {
                    return x;
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("convertToEntityAttribute转换错误"+e.getMessage());
        }
        throw new RuntimeException("找不到数据列 " + dbData);
    }
}
